<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  ElMessageBox
  // ElTag,
  // ElMessageBox
} from 'element-plus'

import { Table } from '@/components/Table'

import { sysDictRelsApi } from '@/api/dict'

import { spCostAddAdminApi, spCostDelApi, spCostEditApi, spCostListApi } from '@/api/cy/xSign'
// import { adminFaMedicalOrderListApi, adminFaMedicalOrderEditApi } from '@/api/fa/medical'
import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive
} from 'vue'
// import Edit from './components/Edit.vue'
import See from './components/See.vue'
// import Assets from './components/Assets.vue'
import Add from './components/Add.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const dictRelsData = ref() // 联动数据
const searchRef = ref() // 搜索的标签
// const breedSubData: any = ref([]) // 品种的枚举

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
// const iconAssets = useIcon({ icon: 'fluent-emoji-high-contrast:cow-face' })
const iconDelete = useIcon({ icon: 'material-symbols:delete-outline' })
// const iconCompleted = useIcon({ icon: 'fluent-mdl2:completed' })
// const iconAudit = useIcon({ icon: 'icon-park-outline:audit' })
// const iconExport = useIcon({ icon: 'arcticons:exportcontacts' })

const defaultTime = ref<[Date, Date]>([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
// const breedGetSub = async (breed_value) => {
//   // console.log('breed_value', breed_value, !breed_value)
//   if (!breed_value) {
//     breedSubData.value = []
//   } else {
//     let breedData = dictRelsData.value.find((item) => {
//       return item.value == breed_value
//     })
//     breedSubData.value = breedData.children
//   }
// }

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spCostListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

// 选择畜别的时候触发，处理品种类容
// const breedChange = (value) => {
//   breedGetSub(value)
//   const new_search = unref(searchRef)
//   new_search.setData({ ...new_search.getData(), breed_sub: '' })
// }

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 200,
    search: {
      show: false
    }
  },
  {
    field: 'code',
    label: '费用编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'type',
    label: '费用类型',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('zcfy_type', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.zcfy_type
      },
      show: true
    }
  },
  {
    field: 'start_date',
    label: '发生日期',
    width: 150,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  },
  // {
  //   field: 'breed',
  //   label: '畜别',
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return getDictLabel('breed', cellValue)
  //   },
  //   width: 100,
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: dict.breed,
  //       onChange: breedChange
  //     },
  //     show: true
  //   }
  // },
  // {
  //   field: 'breed_sub',
  //   label: '品种',
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return getDictLabel('breed_sub', cellValue)
  //   },
  //   width: 150,
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: breedSubData
  //     },
  //     show: true
  //   }
  // },
  {
    field: 'number',
    label: '数量',
    width: 80,
    search: {
      show: false
    }
  },
  {
    field: 'totalAmount',
    label: '总金额',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 150,
    table: {
      show: true
    }
  },
  // {
  //   field: 'update_user_name',
  //   label: '创建人',
  //   width: 80,
  //   form: {
  //     show: false
  //   }
  // },
  {
    field: 'action',
    width: 150,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

// 删除
const apiDel = async (id) => {
  let delRes = await spCostDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      // tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'assets':
      dialogTitle.value = row.pasture_org_name + '-资产列表'
      // tableObject.currentRow = { ...row, owner_sys_role_id: 2, owner_sys_role_name: '组织管理员' }
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个疫苗注射单吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row.id)
          apiDel(Number(row.id))
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref()
const loading = ref(false)
const checkedAll = ref(false)
const ids = ref([])

const save = async () => {
  const edit: any = unref(editRef)
  const dataInfo = await edit?.data

  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          await edit?.elFormRef?.validate(async (isValid) => {
            if (isValid) {
              const methodsAdd = await edit?.methods
              const { getSelections } = methodsAdd
              let selectDataInfo = ref({})
              // saveLoading.value = true
              await getSelections().then((res: any) => {
                selectDataInfo.value = res
                checkedAll.value = res.allCheck.value ? res.allCheck.value : false
                if (checkedAll.value) {
                  ids.value = res.noSelectData.value.map((element) => element.id)
                } else {
                  if (res.selectData.value.length > 0) {
                    ids.value = res.selectData.value.map((element) => element.id)
                  }
                }
              })
              const data = (await edit?.getFormData()) as any
              console.log(dataInfo, data, 'dataInfo')
              console.log(checkedAll.value, 'checkedAll.value')
              console.log(ids.value, 'selected')
              let res = await spCostEditApi({
                id: data.id,
                pasture_org_id: data.pasture_org_id,
                pasture_dept_id: data.pasture_dept_id,
                admin_org_id: data.admin_org_id,
                admin_dept_id: data.admin_dept_id,
                admin_user_id: data.admin_user_id,
                type: data.type,
                breed: edit.Search.breed ? edit.Search.breed : '',
                breed_sub: edit.Search.breed_sub ? edit.Search.breed_sub : '',
                earcon_code: edit.Search.earcon_code ? edit.Search.earcon_code : '',
                asset_code: edit.Search.asset_code ? edit.Search.asset_code : '',
                note: data.note,
                checkedAll: checkedAll.value,
                number: data.numbre,
                selected: ids.value,
                detailed: data.detailed,
                start_date: data.start_date,
                my_dept_id: data.pasture_dept_id
              })
                .catch(() => {})
                .finally(() => {
                  loading.value = false
                })
              console.log(res, 'add')
              if (res) {
                dialogVisible.value = false
                tableObject.currentPage = 1
                getList()
              }
            }
          })
        }
      })
      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const methodsAdd = await edit?.methods
          const { getSelections } = methodsAdd
          let selectDataInfo = ref({})
          // saveLoading.value = true
          await getSelections().then((res) => {
            selectDataInfo.value = res
            checkedAll.value = res.allCheck.value ? res.allCheck.value : false
            if (res.allCheck.value) {
              if (res.noSelectData.value.length > 0) {
                ids.value = res.noSelectData.value.map((element) => element.id)
              }
            } else {
              if (res.selectData.value.length > 0) {
                // console.log(res.selectData.value, 'res.selectData.value')
                ids.value = res.selectData.value.map((element) => element.id)
              }
            }
          })
          const data = (await edit?.getFormData()) as any
          console.log(dataInfo, data, 'dataInfo')
          console.log(checkedAll.value, 'checkedAll.value')
          console.log(ids.value, 'selected')
          let res = await spCostAddAdminApi({
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_name,
            type: data.type,
            breed: edit.Search.breed ? edit.Search.breed : '',
            breed_sub: edit.Search.breed_sub ? edit.Search.breed_sub : '',
            earcon_code: edit.Search.earcon_code ? edit.Search.earcon_code : '',
            asset_code: edit.Search.asset_code ? edit.Search.asset_code : '',
            note: data.note,
            checkedAll: checkedAll.value,
            number: data.numbre,
            selected: Object.values(ids.value),
            detailed: data.detailed,
            start_date: data.start_date,
            my_dept_id: data.pasture_dept_name
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          console.log(res, 'add')
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 初始化 start ******************************/
const init = async () => {
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
  console.log(tableObject.tableList, 'List,数据')
}
init()
</script>

<template>
  <ContentWrap>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :loading="tableObject.loading"
      :data="tableObject.tableList"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="编辑" />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <!-- <ElButton circle :icon="iconAssets" @click="action('assets', row)" title="资产列表" /> -->
        <ElButton circle :icon="iconDelete" @click="action('del', row)" title="删除" />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add
      v-if="actionType == 'edit'"
      ref="editRef"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <Add v-if="actionType == 'add'" ref="editRef" />

    <!-- <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    /> -->

    <template #footer>
      <ElButton
        v-if="actionType !== 'see' && actionType !== 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
